package com.wlper.lib.view.loading;

import com.android.nearshop.R;
import com.wlper.lib.uitls.ViewUtils;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

/**
 * 采用Frame Animation的方式来显示加载动画
 * 
 * @author wanliang527
 * @date 2014-06-13
 */
public class LoadLayoutWithFrameAnim extends SimpleLoadLayout {

    private final static int DEF_DRAWABLE = R.drawable.wl_anim_loading;

    private AnimationDrawable loadingDrawable;

    public LoadLayoutWithFrameAnim(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    public LoadLayoutWithFrameAnim(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LoadLayoutWithFrameAnim(Context context) {
        super(context);
    }

    @Override
    protected void startLoading() {
        changeClickable(false);
        loadFailedView.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
        ImageView v = (ImageView) findViewById(R.id.image_v_loading);
        if (v.getBackground() == null)
            v.setBackgroundResource(DEF_DRAWABLE);
        try {
            loadingDrawable = (AnimationDrawable) v.getBackground();
            if (!loadingDrawable.isRunning())
                loadingDrawable.start();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void stopLoading(boolean isSuccess) {
        if (loadingDrawable != null && loadingDrawable.isRunning())
            loadingDrawable.stop();
        loadingView.setVisibility(View.GONE);
        loadFailedView.setVisibility(View.GONE);
        changeClickable(false);
        if (!isSuccess) {
            loadFailedView.setVisibility(View.VISIBLE);
            changeClickable(true);
        }
    }

    public void setLoadingDrawable(AnimationDrawable drawable) {
        ImageView i = (ImageView) findViewById(R.id.image_v_loading);
        if (drawable == null || i == null)
            return;
        if (loadingDrawable != null && loadingDrawable.isRunning())
            loadingDrawable.stop();

        loadingDrawable = drawable;
        i.setBackgroundDrawable(drawable);
        drawable.start();
    }

    public void setLoadingDrawable(int anim_list) {
        try {
            Drawable d = getResources().getDrawable(anim_list);
            setLoadingDrawable((AnimationDrawable) d);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ClassCastException e1) {
            e1.printStackTrace();
        }
    }



}
